#!/usr/bin/env python

import subprocess
import signal
import sys
import os
import datetime
import argparse


os.environ['HYDROGEN_MODE'] = 'test'


def handler(signum, frame):
    sys.exit(0)


def clear():
    subprocess.call(["clear"])


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-w', dest="watch", action='store_true')
    args = parser.parse_args()

    lasttest = None
    while args.watch:
        pipe = os.open('triggertest.pipe', os.O_RDONLY)
        clear()
        finput = os.fdopen(pipe)
        line = finput.readline()
        fname = line.split(' ')[0]
        if os.path.basename(fname).startswith('test'):
            lasttest = fname
        if lasttest:
            subprocess.call(['py.test', lasttest])
        finput.close()
        print datetime.datetime.now()
    else:
        subprocess.call(['py.test'])

signal.signal(signal.SIGINT, handler)

if __name__ == '__main__':
    main()
